/**
 * 表结构维护 - 编辑页面
 * @author miaoyl
 * @date 2018/01/04
 */
define(function () {

    var self,
        app = win.app,
        doc = document,
        layui = win.layui,
        table,
        form,
        vueData = {
            isAdd: false,
            isDetail: false,
            dbType: true,
            form: {
                mx_list:[]
            },
            rules: {
                TABLE_ID: [
                    {required: true, message: '不可为空', trigger: 'blur'}
                ],
                TABLE_NAME: [
                    {required: true, message: '不可为空', trigger: 'blur'}
                ]
            },
            selectOptions: {
                sys_column_types:[]
            }
        },
        edit_table_where = {
            TABLE_ID:''
        },
        cols = [[
            {field: 'SEQ', type:'checkbox'},
            {field: 'COLUMN_ID', width: 120, title: '栏位编码',edit: 'text'}
            , {field: 'COLUMN_NAME', width: 120, title: '栏位名称',edit: 'text'}
            , {field: 'COLUMN_TYPE', width: 100, title: '栏位类型',edit: 'select',
                filterDatas: vueData.selectOptions.sys_column_types
            }
            , {field: 'COLUMN_LENGTH', width: 100, title: '栏位长度',edit: 'text'}
            , {field: 'COLUMN_SCALE', width: 100, title: '小数位',edit: 'text'}
            , {field: 'IS_PRIMARY_KEY', width: 100, title: '是否主键', /*event:'clickKey',*/
                filterDatas: app.datas_('sys_n_y'),
                edit:'select'
                /*templet:function (data) {
                    var html = '<input type="checkbox" name="IS_PRIMARY_KEY" lay-skin="primary" lay-filter="switchKey" value="'+data.IS_PRIMARY_KEY+'"'+ (data.IS_PRIMARY_KEY=='Y'? 'checked': '')  +'>';
                    return html;
                }*/
            }
            , {field: 'IS_NULL', width: 100, title: '是否为空',filterDatas: app.datas_('sys_n_y'),
                edit:'select'
                /*templet:function (data) {
                    var html = '<input type="checkbox" name="IS_NULL" lay-skin="primary" lay-filter="switchNull" value="'+data.IS_NULL+'"'+ (data.IS_NULL=='Y'? 'checked': '')  +'>';
                    return html;
                }*/
            }
            , {field: 'DEAFAULT_VALUE', width: 100, title: '默认值',edit: 'text'}
            , {field: 'ORIGINAL_VALUE', width: 200, title: '原始值',hide: true}
            , {field: 'ORIGINAL_IS_NULL', width: 200, title: '是否为空原始值',hide: true}
            , {field: 'FLAG', width: 200, title: '是否被修改',hide: true}
        ]],
        callObj,
        columnsTable,
        tableData=[],
        layOpenIndex
    ;

    var tableEdit = app.Module.extend({
        init: function () {
            self = this;
            self._super({
                _tag: 'table_edit',
            }, win);
        },

        initTable: function () {
            layui.use(['table'], function () {
                table = layui.table;
                form = layui.form;
                columnsTable = table.render({
                    elem: app.getByid(doc, 'edit_table'),
                    data:tableData,
                    id: 'edit_table',
                    height: '400px',
                    cols: cols
                });

                var tipsIndex=null;

                $(doc).on('click', function(){
                    tipsIndex&&layer.close(tipsIndex);
                });

                //监听key值操作
                /*form.on('checkbox(switchKey)', function(obj){
                    console.log('obj',obj);
                    var tableData = columnsTable.getDatas();
                    var elem = $(obj.elem);
                    var trElem = elem.parents('tr');
                    tableData[trElem.data('index')][elem.attr('name')] = obj.elem.checked ? 'Y': 'N';
                    /!*tableData[trElem.data('index')]["IS_NULL"] = 'N';
                    tableData[trElem.data('index')]["FLAG"] = 'Y';*!/
                    /!*elem.parents('tr').children().find('input[name="IS_NULL"]')[0].nextSibling.classList.remove("layui-form-checked");
                    elem.parents('tr').children().find('input[name="IS_NULL"]')[0].value = 'N';
                    elem.parents('tr').children()[6].dataset.content = 'N'*!/
                    // form.render('checkbox');
                    // 更新到表格的缓存数据中，才能在获得选中行等等其他的方法中得到更新之后的值
                    // form.render();
                    /!*console.log('elem',elem);
                    console.log('trElem',trElem);
                    console.log('tableData',elem.find('input[type="checkbox"][name="IS_NULL"]'));*!/
                });*/

                //监听null值操作
                /*form.on('checkbox(switchNull)', function(obj){
                    console.log('obj1',obj);
                    var tableData = columnsTable.getDatas();
                    var elem = $(obj.elem);
                    var trElem = elem.parents('tr');
                    // 更新到表格的缓存数据中，才能在获得选中行等等其他的方法中得到更新之后的值
                    tableData[trElem.data('index')][elem.attr('name')] = obj.elem.checked ? 'Y': 'N';
                    tableData[trElem.data('index')]["FLAG"] = 'Y';
                });*/

                table.on('tool(edit_table)', function (obj) {
                    /*if(obj.event == 'clickKey'){
                        console.log('obj.value',obj);
                        var IS_NULL = 'Y';
                        if(obj.data.IS_PRIMARY_KEY == 'Y'){
                            IS_NULL = 'N';
                        }
                        var html = '<input type="checkbox" name="IS_NULL" lay-skin="primary" lay-filter="switchKey" value="'+IS_NULL+'"'+ (IS_NULL=='Y'? 'checked': '') + (obj.data.IS_PRIMARY_KEY=='Y'? 'disabled': '') +'>';
                        console.log('html',html);
                        obj.updateOfEdit({
                            IS_NULL: IS_NULL,
                            FLAG: 'Y'
                        });
                        form.render('checkbox');
                    }*/
                });

                //监听单元格编辑
                table.on('edit(edit_table)', function (obj) {
                    if(obj.field == 'COLUMN_LENGTH'){
                        if(vueData.dbType) {
                            if (obj.data.COLUMN_TYPE == 'DATE' || obj.data.COLUMN_TYPE == 'DATETIME') {
                                obj.updateOfEdit({
                                    COLUMN_LENGTH: ''
                                });
                                app.showMessage("栏位类型为日期时，长度为空！");
                                return;
                            }
                            if (obj.data.COLUMN_TYPE == 'TEXT') {
                                obj.updateOfEdit({
                                    COLUMN_LENGTH: ''
                                });
                                app.showMessage("栏位类型为TEXT时，长度为空！");
                                return;
                            }
                            if (obj.data.COLUMN_TYPE == 'VARCHAR' || obj.data.COLUMN_TYPE == 'DECIMAL') {
                                var reg = /^[0-9]*$/;
                                if (!reg.test(obj.value)) {
                                    obj.updateOfEdit({
                                        COLUMN_LENGTH: ''
                                    });
                                    app.showWarning("长度必须为正整数！");
                                    return;
                                }
                            }
                        }else {
                            if (obj.data.COLUMN_TYPE == 'DATE' || obj.data.COLUMN_TYPE == 'TIMESTAMP') {
                                obj.updateOfEdit({
                                    COLUMN_LENGTH: ''
                                });
                                app.showMessage("栏位类型为日期时，长度为空！");
                                return;
                            }
                            if (obj.data.COLUMN_TYPE == 'CLOB') {
                                obj.updateOfEdit({
                                    COLUMN_LENGTH: ''
                                });
                                app.showMessage("栏位类型为CLOB时，长度为空！");
                                return;
                            }
                            if (obj.data.COLUMN_TYPE == 'VARCHAR2' || obj.data.COLUMN_TYPE == 'NUMERIC') {
                                var reg = /^[0-9]*$/;
                                if (!reg.test(obj.value)) {
                                    obj.updateOfEdit({
                                        COLUMN_LENGTH: ''
                                    });
                                    app.showWarning("长度必须为正整数！");
                                    return;
                                }
                            }
                        }
                        obj.updateOfEdit({
                            FLAG: 'Y'
                        })
                    }else if(obj.field == 'COLUMN_SCALE'){
                        if(vueData.dbType) {
                            if (obj.data.COLUMN_TYPE != 'DECIMAL') {
                                obj.updateOfEdit({
                                    COLUMN_SCALE: ''
                                });
                                app.showWarning("仅数字型可填写小数位！");
                                return;
                            }
                        }else {
                            if (obj.data.COLUMN_TYPE != 'NUMERIC') {
                                obj.updateOfEdit({
                                    COLUMN_SCALE: ''
                                });
                                app.showWarning("仅数字型可填写小数位！");
                                return;
                            }
                        }
                        var reg = /^\d+$/;
                        if (!reg.test(obj.value)) {
                            obj.updateOfEdit({
                                COLUMN_SCALE: ''
                            });
                            app.showWarning("小数位必须为非负整数！");
                            return ;
                        }
                        obj.updateOfEdit({
                            FLAG: 'Y'
                        })
                    }else if(obj.field == 'IS_PRIMARY_KEY'){
                        var IS_NULL = 'Y';
                        if(obj.value == 'Y'){
                            IS_NULL = 'N';
                        }
                        if(IS_NULL != obj.data.IS_NULL){
                            obj.updateOfEdit({
                                IS_NULL_old: obj.data.IS_NULL
                            });
                        }
                        obj.updateOfEdit({
                            IS_NULL: IS_NULL,
                            FLAG: 'Y'
                        });
                    }else if(obj.field == 'IS_NULL'){
                        if(obj.data.IS_PRIMARY_KEY == 'Y' && obj.value == 'Y'){
                            obj.updateOfEdit({
                                IS_NULL: 'N',
                                FLAG: 'Y'
                            });
                            app.showMessage("栏位为主键时，字段不允许为空！");
                            return;
                        }
                        obj.updateOfEdit({
                            FLAG: 'Y'
                        });
                    }else if(obj.field == 'COLUMN_ID'){
                        /*console.log('obj1',obj);*/
                        var flag = false;
                        var count = 0;
                        var listData = columnsTable.getDatas();
                        listData.some(function (item) {
                            if(item.COLUMN_ID == obj.value){
                                count ++;
                                if(count > 1) {
                                    flag = true;
                                    return true;
                                }
                            }
                        });
                        if(flag){
                            obj.updateOfEdit({
                                COLUMN_ID: ''
                            });
                            app.showMessage("栏位编码已存在");
                            return;
                        }
                        obj.updateOfEdit({
                            FLAG: 'Y'
                        });
                    }else if(obj.field == 'COLUMN_TYPE'){
                        //console.log('obj',obj);
                        obj.updateOfEdit({
                            COLUMN_LENGTH: '',
                            DEAFAULT_VALUE: '',
                            FLAG: 'Y'
                        });
                    }else if(obj.field == 'DEAFAULT_VALUE'){
                        if(vueData.dbType) {
                            if (obj.data.COLUMN_TYPE == 'DATE' || obj.data.COLUMN_TYPE == 'DATETIME') {
                                obj.updateOfEdit({
                                    DEAFAULT_VALUE: ''
                                });
                                app.showWarning("日期字段不允许给默认值！");
                                return;
                            }
                        }else {
                            if (obj.data.COLUMN_TYPE == 'DATE' || obj.data.COLUMN_TYPE == 'TIMESTAMP') {
                                obj.updateOfEdit({
                                    DEAFAULT_VALUE: ''
                                });
                                app.showWarning("日期字段不允许给默认值！");
                                return;
                            }
                        }
                        obj.updateOfEdit({
                            FLAG: 'Y'
                        });
                    }else if(obj.field == 'COLUMN_NAME'){
                        obj.updateOfEdit({
                            FLAG: 'Y'
                        });
                    }
                });
            });
        },

        tableReload: function (listData) {
            self._reloadTable({id: 'edit_table', data: listData});
        },

        editTable: function (listData) {
            app.ajax({
                xurl: 'sys/table/edit',
                xdata: listData,
                toJsonStr: true,
                // okmsg: self._moduleName + '修改成功',
                cb: function (result) {
                    if (result.ok) {
                        if(result.data.data.code == 200){
                            //同步更新缓存对应的值
                            //callObj.update(result.xdata);
                            app.pageModule('columns').reloadTableCurr();
                            layer.close(layOpenIndex);
                            app.showSuccess(result.data.data.msg);
                        }else if(result.data.data.code == 500) {
                            //app.showError(result.data.data.msg);
                            /*app.confirm({
                                msg:result.data.data.msg,
                                ok:function () {}
                            });*/
                            layui.layer.open({
                                type: 1,
                                shade: false,
                                title: false, //不显示标题
                                area:['600px','400px'],
                                content: result.data.data.msg, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                                cancel: function(){
                                }
                            });
                        }
                    }
                }
            });
        },

        addTable: function (listData) {
            app.ajax({
                xurl: 'sys/table/add',
                xdata: listData,
                toJsonStr: true,
                // okmsg: self._moduleName + '保存成功',
                cb: function (result) {
                    if (result.ok) {
                        if(result){
                            if(result.data.data.code == 200){
                                app.pageModule('columns').reloadTableCurr();
                                layer.close(layOpenIndex);
                                app.showSuccess(result.data.data.msg);
                            }else if(result.data.data.code == 500) {
                                //app.showError(result.data.data.msg);
                                layui.layer.open({
                                    type: 1,
                                    shade: false,
                                    title: false, //不显示标题
                                    area:['600px','400px'],
                                    content: result.data.data.msg, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                                    cancel: function(){
                                    }
                                });
                                /*app.confirm({
                                    msg:result.data.data.msg,
                                    ok: function (e) {
                                        layer.close(layer.index);
                                    }
                                });*/
                            }

                        }
                    }
                }
            });
        },
        _call: function (tagData) {
            layOpenIndex =  tagData.layOpenIndex;
            if(tagData.isDetail){
                vueData.isDetail = true;
            }else {
                vueData.isDetail = false;
            }
            app.ajax({
                async:false,
                xurl: 'sys/table/getdbtype',
                xdata: {},
                cb: function (result) {
                    if(result.ok) {
                        vueData.dbType = result.data.data.dbType;
                        if(result.data.data.dbType){
                            vueData.selectOptions.sys_column_types = app.datas_('sys_column_types');
                            columnsTable.config.cols[0][3].filterDatas = vueData.selectOptions.sys_column_types;
                        }else {
                            vueData.selectOptions.sys_column_types = app.datas_('sys_column_types_oracle');
                            columnsTable.config.cols[0][3].filterDatas = vueData.selectOptions.sys_column_types;
                        }
                    }
                }
            });
            if (tagData.is_add) {
                vueData.isAdd = true;
                app.extendUpLow({
                    target: vueData.form,
                    res: {},
                    reset: true
                });
                self.tableReload([]);
            } else {
                vueData.isAdd = false;
                callObj = tagData.obj;
                app.extendUpLow({
                    target: vueData.form,
                    res: callObj.data,
                    reset: true
                });
                edit_table_where.TABLE_ID = tagData.obj.data.TABLE_ID;
                app.ajax({
                    xurl: 'sys/table/getTableEdit',
                    xdata: edit_table_where,
                    loading: true,
                    cb: function (result) {
                        if(result.ok){
                            self.tableReload(result.data.data);
                        }
                    }
                });
            }
        },
        _ready: function () {
            vueData.form = app.fields_(['sys_table_column']);
            new Vue({
                el: '#table_edit',
                data: vueData,
                methods: {
                    cancel: function () {
                        layer.close(layOpenIndex);
                    },
                    addData:function () {
                        var listData = columnsTable.getDatas();
                        listData.push({
                            SEQ: listData.length + 1,
                            COLUMN_ID: '',
                            COLUMN_NAME: '',
                            COLUMN_TYPE: '',
                            COLUMN_LENGTH: '',
                            COLUMN_SCALE: '',
                            IS_PRIMARY_KEY: 'N',
                            IS_NULL: 'Y',
                            DEAFAULT_VALUE: '',
                            FLAG: 'N'
                        });
                        self.tableReload(listData);
                    },
                    delData:function () {
                        var listData = columnsTable.getDatas();
                        var checkStatus = table.checkStatus('edit_table');
                        if (checkStatus.data.length > 0) {
                            checkStatus.data.forEach(function (v) {
                                if(v.COLUMN_ID != null && v.COLUMN_ID != ''){
                                    listData.removeByMap({
                                        COLUMN_ID: v.COLUMN_ID
                                    });
                                }else {
                                    listData.removeByMap({
                                        SEQ: v.SEQ
                                    });
                                }

                            });
                            self.tableReload(listData);
                        }
                    },
                    sure: function () {
                        this.$refs['form'].validate(function (valid) {
                            if (valid) {
                                var listData = columnsTable.getDatas();
                                var flag = true;
                                if(listData.length == 0){
                                    app.showMessage("表格内容不允许为空！");
                                    return;
                                }
                                listData.some(function (v) {
                                    if(v.COLUMN_ID == '' || v.COLUMN_ID == null){
                                        app.showMessage("栏位编码不允许为空！");
                                        flag = false;
                                        return true;
                                    }
                                    if(v.COLUMN_TYPE == '' || v.COLUMN_TYPE == null){
                                        app.showMessage("栏位类型不允许为空！");
                                        flag = false;
                                        return true;
                                    }
                                    if(vueData.dbType) {
                                        if ((v.COLUMN_TYPE != 'DATE' && v.COLUMN_TYPE != 'DATETIME' && v.COLUMN_TYPE != 'TEXT') && (v.COLUMN_LENGTH == '' || v.COLUMN_LENGTH == null)) {
                                            app.showMessage("除日期和TEXT类型外，其他字段类型长度不允许为空！");
                                            flag = false;
                                            return true;
                                        }
                                    }else {
                                        if ((v.COLUMN_TYPE != 'DATE' && v.COLUMN_TYPE != 'TIMESTAMP' && v.COLUMN_TYPE != 'CLOB') && (v.COLUMN_LENGTH == '' || v.COLUMN_LENGTH == null)) {
                                            app.showMessage("除日期和CLOB类型外，其他字段类型长度不允许为空！");
                                            flag = false;
                                            return true;
                                        }
                                    }
                                })
                                if(flag){
                                    listData.addMap(vueData.form, false);
                                    if (vueData.isAdd) {
                                        self.addTable(listData);
                                    } else {
                                        self.editTable(listData);
                                    }
                                }
                            }
                        });
                    },
                    checkTableID:function () {
                        if (vueData.isAdd) {
                            app.ajax({
                                xurl: 'sys/table/getTableCount',
                                xdata: vueData.form,
                                cb: function (result) {
                                    if (result.ok) {
                                        if (result.data.data.ISEXSIT == 'Y') {
                                            app.showMessage("该表ID已经存在，请重新输入！");
                                            vueData.form.TABLE_ID = '';
                                            return;
                                        }
                                    }
                                }
                            });
                        }
                    }
                },
                watch: {},
                created : function () {
                    self._setEleIsReady('table_edit');
                }
            });

            self.initTable();

        },
        _lazy: function () {
            this._super();
        }
    });

    return new tableEdit();

});